/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets.trip;

import database.Database;
import helper.DateProcess;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Not Stephen
 */
public class AddWaypointServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Connection c = null;
        c = Database.getConnection();
        /*
         location.href ='./AddWaypointServlet?id=' + tripId + 
         * '&startLocation='+startLocation+'
         * &endLocation='+endLocation+
         '&startDate='+startDate+'
         * &endDate='+endDate + wayLocStr + wayDateStr + oWayLocStr + oWayDateStr  ;
         * &wayPtLocation=' + wayPoints[i];
         wayDateStr +='&wayPtDate=' + wayDates[i];
         }
         for(var i = 0; i < wayDates.length;i++){
         oWayLocStr += '&originalWayPtLocation=' + originalLocations[i];
         oWayDateStr +='&originalWayPtDate=' + originalDates[i];
         */
        int tripId = Integer.parseInt(request.getParameter("id"));
        String startLocation = request.getParameter("startLocation");
        String endLocation = request.getParameter("endLocation");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String[] wayPointLocations = request.getParameterValues("wayPtLocation");
        String[] wayPointDates = request.getParameterValues("wayPtDate");
        int originalLength = Integer.parseInt(request.getParameter("ol"));
        if (c != null) {
            try {
                PreparedStatement s = c.prepareStatement("UPDATE trip SET startLocation = ?, endLocation = ?, startDate = ?, endDate = ? WHERE id = ?");
                s.setString(1, startLocation);
                s.setString(2, endLocation);
                s.setString(3, startDate);
                s.setString(4, endDate);
                s.setInt(5, tripId);
                try {
                    s.executeUpdate();
                } catch (SQLException e) {
                }
                int len = (wayPointLocations.length > originalLength ? wayPointLocations.length : originalLength);
                if (originalLength > wayPointLocations.length) {
                    int i = 0;
                    while (i < wayPointLocations.length) {
                        PreparedStatement ss = c.prepareStatement("UPDATE waypoint SET location = ?, date = ? WHERE tripId = ? AND order = ?");
                        ss.setString(1, wayPointLocations[i]);
                        ss.setString(2, wayPointDates[i]);
                        ss.setInt(3, tripId);
                        ss.setInt(4, ++i);
                        try {
                            ss.executeUpdate();
                        } catch (SQLException e) {
                        }
                    }
                    PreparedStatement rm = c.prepareStatement("DELETE FROM waypoint WHERE tripId = ? AND order >= ?");
                    rm.setInt(1, tripId);
                    rm.setInt(2, originalLength);
                    try {
                        rm.executeUpdate();
                    } catch (SQLException e) {
                    }
                }
                if (wayPointLocations.length > originalLength) {
                    int i = 0;
                    while (i < originalLength) {
                        PreparedStatement ss = c.prepareStatement("UPDATE waypoint SET location = ?, date = ? WHERE tripId = ? AND order = ?");
                        ss.setString(1, wayPointLocations[i]);
                        ss.setString(2, wayPointDates[i]);
                        ss.setInt(3, tripId);
                        ss.setInt(4, ++i);
                        try {
                            ss.executeUpdate();
                        } catch (SQLException e) {
                        }
                    }
                    PreparedStatement wPs = c.prepareStatement("SELECT id FROM waypoint ORDER BY id DESC");
                    ResultSet wPsRS = wPs.executeQuery();

                    int wId = 1;
                    if (wPsRS.next()) {
                        wId = wPsRS.getInt("id") + 1;
                    }
                    while (i < wayPointLocations.length) {

                        PreparedStatement ss = c.prepareStatement("INSERT INTO waypoint(id,date,location,order,tripId) VALUES(?,?,?,?,?)");
                        ss.setInt(1, wId++);
                        ss.setString(2, wayPointDates[i]);
                        ss.setString(3, wayPointLocations[i]);
                        ss.setInt(4, ++i);
                        ss.setInt(5, tripId);
                        try {
                            ss.executeUpdate();
                        } catch (SQLException e) {
                        }
                    }
                }
                String locations = startLocation + "|";
                for (int i = 0; i < wayPointLocations.length; i++) {
                    locations += wayPointLocations[i] + "|";
                }
                locations += endLocation;
                String dates = "";//FILL THIS IN
                dates += startDate + "|";
                for (int i = 0; i < wayPointDates.length; i++) {
                    dates += wayPointDates[i] + "|";
                }
                dates += endDate;
                //location.href =
                // "./GoToMapServlet?locations="+ locations + "&dates=" + dates + "&tripId=" + tripId;
                RequestDispatcher rd = request.getRequestDispatcher("./GoToMapServlet?locations=" + locations + "&dates=" + dates + "&tripId=" + tripId);
                rd.forward(request, response);
            } catch (SQLException ex) {
                Logger.getLogger(AddWaypointServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }





        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet EditTripServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet EditTripServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
